import baseUrl from "@/common/config.js";
// #ifdef APP-PLUS
var COS = require("@/common/js_sdk/cos-jdk/cos-wx-sdk-v5.js")
// var fileSelect = uni.requireNativePlugin("Aq-fileSelect");
// #endif
// #ifdef H5
var COS = require("@/common/js_sdk/cos-jdk/h5/cos-js-sdk-v5.min.js");
// #endif
export function uploadAttachment (callback, type = ['image/*', 'video/*', 'audio/*']) {
	uni.showLoading({
		title: '加载中'
	});
	var H5Type = type.join(",")
	var appType = type.join("|")
	// #ifdef H5
	var x = document.createElement('input');
	var ext
	x.setAttribute('type', 'file');
	x.setAttribute('accept', H5Type);
	x.click();
	x.onchange = function () {
		ext = this.files[0].type.split('/')[1]
		putFile(this.files[0], ext, callback)
	};
	uni.hideLoading()
	// #endif
	// #ifdef APP-PLUS
	chooseFile((res) => {
		if (res != null) {
			var path1 = "file://" + res
			console.log("path1>>>>>>>>", path1)
			putFile(path1, null, callback)
		}
	}, appType)
	// fileSelect.openFile({
	// 	'model': "media", //"media"和"folder" //不填默认media  
	// 	'size': '1', //选择总数量
	// 	'type': ['image','mp3','mp4'] //image,xls,word,ppt,pdf,mp3,mp4  不填默认全部
	// }, (res) => {
	// 	res.data.forEach(item =>{
	// 	var path1 = "file://" + item.path
	// 	putFile(path1, null, callback)
	// 	})
	// })
	uni.hideLoading()
	// #endif
}
// 上传服务器的方法
function putFile (filePath, ext1, callback) {
	//获取后缀
	var filarr = null
	var ext = null
	if (ext1) {
		ext = ext1
	} else {
		filarr = filePath.split('.')
		ext = filarr[filarr.length - 1]
	}
	console.log("ext>>>>>>>>>>", ext)
	// 异步获取临时密钥
	var data, credentials, bucket, region, filename, url
	uni.request({
		url: baseUrl.getTempKey,
		method: "POST",
		data: {
			// 用户id
			unid: 1,
			// 文件类型
			type: 'image',
			ext: ext
		},
		success: (result) => {
			console.log("result", result)
			data = result.data;
			bucket = data.data.bucket
			region = data.data.region
			filename = data.data.filepath
			credentials = data.data.credentials;
			//实例化
			var cos = new COS({
				getAuthorization: function (options, callback) {
					callback({
						TmpSecretId: credentials.tmpSecretId,
						TmpSecretKey: credentials.tmpSecretKey,
						XCosSecurityToken: credentials.sessionToken,
						// 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
						StartTime: data.data.startTime, // 时间戳，单位秒，如：1580000000
						ExpiredTime: data.data.expiredTime, // 时间戳，单位秒，如：1580000900
					});
				}
			});
			uni.showLoading({
				title: '上传中'
			});
			// #ifdef APP-PLUS 
			cos.postObject({
				Bucket: bucket,
				Region: region,
				Key: filename,
				FilePath: filePath,
				onProgress: function (info) {
					console.log(JSON.stringify(info));
				}
			}, requestCallback)
			// #endif
			// #ifdef H5
			cos.putObject({
				Bucket: bucket,
				Region: region,
				Key: filename,
				StorageClass: "STANDARD",
				Body: filePath,
				onProgress: function (info) {
					console.log(JSON.stringify(info));
				},
			}, requestCallback)
			// #endif
		}
	});
	// 回调统一处理函数
	var requestCallback = (err, data) => {
		if (err && err.error) {
			uni.showModal({
				title: '返回错误',
				content: '请求失败：' + (err.error.Message || err.error) + '；状态码：' + err.statusCode,
				showCancel: false
			});
			uni.hideLoading()
		} else if (err) {
			uni.showModal({
				title: '请求出错',
				content: '请求出错：' + err + '；状态码：' + err.statusCode,
				showCancel: false
			});
			uni.hideLoading()
		} else {
			url = 'http://' + data.Location
			uni.hideLoading()
			callback({successUrl:url})
		}
	};
}

function getObjectURL (file) {
	let url = null;
	if (window.createObjectURL != undefined) { // basic
		url = window.createObjectURL(file);
	} else if (window.webkitURL != undefined) { // webkit or chrome
		url = window.webkitURL.createObjectURL(file);
	} else if (window.URL != undefined) { // mozilla(firefox)
		url = window.URL.createObjectURL(file);
	}
	return url;
}

function chooseFile (callback, acceptType) { //acceptType为你要查的文件类型"image/*"，"audio/*"，"video/*;image/*"  // intent.setType("image/*");//intent.setType("audio/*"); //选择音频//intent.setType("video/*;image/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
	var CODE_REQUEST = 1000;
	var main = plus.android.runtimeMainActivity();
	if (plus.os.name == 'Android') {
		var Intent = plus.android.importClass('android.content.Intent');
		var intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		if (acceptType) {
			intent.setType(acceptType);
		} else {
			intent.setType("*/*");
		}
		main.onActivityResult = function (requestCode, resultCode, data) {
			if (requestCode == CODE_REQUEST) {
				var uri = data.getData();
				plus.android.importClass(uri);
				var Build = plus.android.importClass('android.os.Build');
				var isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
				var DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');
				// DocumentProvider
				if (isKitKat && DocumentsContract.isDocumentUri(main, uri)) {
					console.log("版本大于 4.4 ");
					// ExternalStorageProvider
					if ("com.android.externalstorage.documents" == uri.getAuthority()) {
						var docId = DocumentsContract.getDocumentId(uri);
						var split = docId.split(":");
						var type = split[0];
						if ("primary" == type) {
							var Environment = plus.android.importClass('android.os.Environment');
							callback(Environment.getExternalStorageDirectory() + "/" + split[1]);
						} else {
							var System = plus.android.importClass('java.lang.System');
							var sdPath = System.getenv("SECONDARY_STORAGE");
							if (sdPath) {
								callback(sdPath + "/" + split[1]);
							}
						}
					}
					// DownloadsProvider
					else if ("com.android.providers.downloads.documents" == uri.getAuthority()) {
						var id = DocumentsContract.getDocumentId(uri);
						var ContentUris = plus.android.importClass('android.content.ContentUris');
						var contentUri = ContentUris.withAppendedId(
							//    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
							Uri.parse("content://downloads/public_downloads"), id);
						callback(getDataColumn(main, contentUri, null, null));
					}
					// MediaProvider
					else if ("com.android.providers.media.documents" == uri.getAuthority()) {
						var docId = DocumentsContract.getDocumentId(uri);
						var split = docId.split(":");
						var type = split[0];
						var MediaStore = plus.android.importClass('android.provider.MediaStore');
						if ("image" == type) {
							contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
						} else if ("video" == type) {
							contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
						} else if ("audio" == type) {
							contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
						}
						console.log("contentUri",contentUri)
						var selection = "_id=?";
						var selectionArgs = new Array();
						selectionArgs[0] = split[1];
						callback(getDataColumn(main, contentUri, selection, selectionArgs));
					}
				}
				// MediaStore (and general)
				else if ("content" == uri.getScheme()) {
					callback(getDataColumn(main, uri, null, null));
				}
				// File
				else if ("file" == uri.getScheme()) {
					callback(uri.getPath());
				}
			}
		}
		main.startActivityForResult(intent, CODE_REQUEST);
	}
}

function getDataColumn (main, uri, selection, selectionArgs) {
	plus.android.importClass(main.getContentResolver());
	let cursor = main.getContentResolver().query(uri, ['_data'], selection, selectionArgs, null);
	if (cursor == null) {
		 uni.showToast({
			title: '请从图库或文件管理中选择',
			icon: 'none',
			duration: 1500
		})
	}
	plus.android.importClass(cursor);
	if (cursor != null && cursor.moveToFirst()) {
		plus.android.importClass(cursor);
		var column_index = cursor.getColumnIndexOrThrow('_data');
		var result = cursor.getString(column_index)
		cursor.close();
		return result;
	}
	return null;
}
